﻿using Microsoft.Extensions.DependencyInjection;
using SqlSugar;

namespace Lightworks.Core.Repository
{
    public static class SqlSugarBuilderExtensions
    {
        public static IServiceCollection UseSqlSugar(this IServiceCollection services, DBConfig? config)
        {
            //注册上下文：AOP里面可以获取IOC对象，如果有现成框架比如Furion可以不写这一行
            services.AddHttpContextAccessor();
            //注册SqlSugar
            var squlSugar = services.AddSingleton<ISqlSugarClient>(s =>
            {
                SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig
                {
                    DbType = (DbType)Enum.ToObject(typeof(DbType),config.DBType),
                    ConnectionString = config.ConnectionString,
                    IsAutoCloseConnection = true,
                    ConfigureExternalServices = new ConfigureExternalServices()
                    {
                        EntityService = (x, p) => //处理列名
                        {
                            //最好排除DTO类
                            p.DbColumnName = UtilMethods.ToUnderLine(p.DbColumnName);//ToUnderLine驼峰转下划线方法
                        },
                        EntityNameService = (x, p) => //处理表名
                        {
                            //最好排除DTO类
                            p.DbTableName = UtilMethods.ToUnderLine(p.DbTableName);//ToUnderLine驼峰转下划线方法
                        }
                    }
                }, 
                db =>
                {
                   //单例参数配置，所有上下文生效
                   db.Aop.OnLogExecuting = (sql, pars) =>
                   {
                       Console.WriteLine(sql);
                   };
                    db.Aop.DataExecuting = (oldValue, entity) => {
                        if (entity.PropertyName == "CreatedAt" 
                        && entity.OperationType == DataFilterType.InsertByObject) 
                        {
                            entity.SetValue(DateTime.Now);
                        }
                        if (entity.PropertyName == "UpdateAt" 
                        && entity.OperationType == DataFilterType.UpdateByObject)
                        {
                            entity.SetValue(DateTime.Now);
                        }
                    };
               });;
                return sqlSugar;
            });
            services.AddScoped(typeof(SugarRepository<>));
            //services.AddUnitOfWork();
            return services;
        }
    }
}
